<?php
namespace app\weixin\model;
use think\Config;
use think\Cache;
use app\weixin\model\Wechat;
use app\weixin\model\WeixinApp;
class TPWechat extends Wechat{
  public $weixin_app_id;

  public function __construct($appid){
    $AppModel = new WeixinApp();
    if(is_numeric($appid)){
      $field_name = "id";
    }else{
      $field_name = "appid";
    }
    
    $app_info = $AppModel->field("id, appid, appsecret, token, encodingaeskey")
                            ->where($field_name, $appid)->find();
    if(empty($app_info)){
      $this->weixin_app_id = 0;
      $app_info = [];
    }else{
      $this->weixin_app_id = $app_info["id"];
    }
    parent::__construct($app_info);
  }

  /**
   * log overwrite
   * @see Wechat::log()
   */
  protected function log($log){
    if ($this->debug) {
      if (function_exists($this->logcallback)) {
        if (is_array($log)) $log = print_r($log,true);
        return call_user_func($this->logcallback,$log);
      }elseif (class_exists('Log')) {
        Log::write('wechat：'.$log, Log::DEBUG);
        return true;
      }
    }
    return false;
  }

  /**
   * 重载设置缓存
   * @param string $cachename
   * @param mixed $value
   * @param int $expired
   * @return boolean
   */
  protected function setCache($cachename,$value,$expired){
    return Cache::set($cachename,$value,$expired);
  }

  /**
   * 重载获取缓存
   * @param string $cachename
   * @return mixed
   */
  protected function getCache($cachename){
    return Cache::get($cachename);
  }

  /**
   * 重载清除缓存
   * @param string $cachename
   * @return boolean
   */
  protected function removeCache($cachename){
    return Cache::rm($cachename);
  }

  /**
   * 重载Wechat的checkAuth
   * @param string $media_id 媒体文件id
   * @param boolean $is_video 是否为视频文件，默认为否
   * @return raw data
   */
  public function getMedia($media_id,$is_video=false){
    $result=parent::getMedia($media_id, $is_video);

    if($result){
      return $result;
    }else{
      $time = date('Y-m-d H:i:s', time());
      $err="—————errCode:".$this->errCode."——————errMsg:".$this->errMsg."——————time:".$time."——————\n";
      file_put_contents("error_log.txt", $err,FILE_APPEND);
      return false;
    }
  }

  /**
   * 重写Wechat里的checkAuth方法
   * @Author zhanghong
   * @Date   2017-04-18
   * @param  string     $appid     [description]
   * @param  string     $appsecret [description]
   * @param  string     $token     [description]
   * @return [type]                [description]
   */
  public function checkAuth($appid='',$appsecret='',$token=''){
    $access_token = false;
    $environment = Config::get("environment");
    if($environment == "production"){
      $access_token = parent::checkAuth($appid, $appsecret, $token);
    }else{
      $action_path = url("weixin/index/access_token", ["appid" => $this->appid]);
      $production_host = Config::get("production_host");
      $url = $production_host.$action_path;
      $result = $this->http_get($url);
      if ($result){
        $json = json_decode($result, true);
        if (is_array($json) && isset($json['access_token'])) {
          $access_token = $json['access_token'];
          $this->access_token = $access_token;
        }
      }
    }
    return $access_token;
  }

  /**
   * 获取JSAPI授权TICKET
   * @param string $appid 用于多个appid时使用,可空
   * @param string $jsapi_ticket 手动指定jsapi_ticket，非必要情况不建议用
   */
  public function getJsTicket($appid='',$jsapi_ticket=''){
    $jsapi_ticket = false;
    $environment = Config::get("environment");
    if($environment == "production"){
      $jsapi_ticket = parent::getJsTicket($appid, $jsapi_ticket);
    }else{
      $action_path = url("Weixin/Index/js_ticket", ["appid" => $this->appid]);
      $production_host = Config::get("production_host");
      $url = $production_host.$action_path;
      $result = $this->http_get($url);
      if ($result){
        $json = json_decode($result, true);
        if (is_array($json) && isset($json['js_ticket'])) {
          $jsapi_ticket = $json['js_ticket'];
          $this->jsapi_ticket = $jsapi_ticket;
        }
      }
    }
    return $jsapi_ticket;
  }
}